/* 
 * ebiz front
 * 
 * productTemplate.js
 * 
 * @author allen
 * 
 */
//show the product View
/*
function render(){
    var defaultItemId = productData.show_itemid;
    var imageSize = "280.png";
    var pubimgroot = productData.nullImgSrc.pubimgroot;
    var templateName = productData.nullImgSrc.templateName;
    var src;
    //if(defaultItemId != 0){ //the DB already set the default value
        defaultSrc = productData["item_"+defaultItemId].main_image_url;
    //}else{ //the DB not set the default_item value
    //    defaultItemId = productData.show_itemid;    //set the defaultItemId is random value
    //    defaultSrc = "";
    //}
    if(defaultSrc != "" && defaultSrc != null){
        src = defaultSrc+imageSize;
    }else{
        //defaultSrc = productData["item_"+defaultItemId].main_image_url;
        src = "http://"+pubimgroot+"/t/"+templateName+"/image/product"+"_"+imageSize;
    }
    //defaultSrcArray = new Array();  //get the different color image , put in this array
    //defaultSrcArray = generateAttrArray();
    //itemIdArray = showProductOtherImg(defaultSrcArray);
    var srcs = productData["item_"+defaultItemId].image_url;

    showItemDefaultImg(src); //show the default image(the largest image)
    
    showItemOtherImg(srcs); //show the diff view of default image(front , backend , side face)

    showPrice(defaultItemId);   //show the product sale price
    
    showAttribute(defaultItemId);   //show the attribute image, ex: the different color and size
    
    showQuantity(defaultItemId);    //show the product quantity of inventory
    
    //showProductColorLabel();

}
*/
function showItemDefaultImg(src, imageSize, magnifySize){     //show the big image of default == 1
	html = "";
    //html += "<img src='"+src+"' alt='"+productData.productTitle+"' width='296' height='300' />";  
    //html += "  \n   <a id='magnifyImage' href='"+src+magnifySize+"'>"; 
    html += "  \n       <img src='"+src+imageSize+"' alt='"+productData.productTitle+"'  /> \n ";  
    //html += "  \n   </a>"; 
    $('#showImg').html("");
    $('#showImg').html(html);
    hiddenBigImgHtml = "   \n <li>  \n ";
    hiddenBigImgHtml += "  \n       <img class='myImg' src='"+src+imageSize+"' alt='' /> \n ";
    hiddenBigImgHtml += "  \n </li> \n ";
    $('#pic_chg_area').html("");
    $('#pic_chg_area').html(hiddenBigImgHtml);
//    $(function() {    
//    $('#magnifyImage').magnify();
//    });
    //defaultImg = $(html);
    //defaultImg.appendTo('#productImage');
}

function showItemOtherImg(srcs){   //show the same item id of all images 
    var html = "";
    var htmlDesc = "";
    var hiddenBigHtml = "";
    if(srcs != "" && srcs != null){
        var imageSize = "400.jpg";
        var picListSize = "400.jpg";
        var magnifySize = "800.jpg";
        var descImgSize = "600.jpg";
        $.each(srcs, function(i, obj){
            i++;
            //html += " \n <div id='productPictureList' > \n ";
            //html += "  \n   <img id='productThunbnail" + i + "' src='"+obj+picListSize+"' alt='"+productData.productTitle+"' onmouseover='showItemDefaultImg(\""+obj+magnifySize+"\");'/>"; 
            html += "  \n   <img id='productThunbnail" + i + "' src='"+obj+picListSize+"' alt='"+productData.productTitle+"' onmouseover='showItemDefaultImg(\""+obj+"\",\""+imageSize+"\",\""+magnifySize+"\");'/>"; 
            htmlDesc += "  \n   <div align='center' style='margin-top:10px;margin-bottom:10px;'><img id='productThunbnail" + i + "' src='"+obj+descImgSize+"' alt='"+productData.productTitle+"' /></div>"; 
            hiddenBigHtml += "  \n   <a href='#"+(i - 1)+"'><img src='"+obj+picListSize+"' alt='"+obj+picListSize+"' /></a>"; 
            //html += "   <img src='"+obj+imageSize+"' alt=''  onclick='showItemDefaultImg(\""+obj+imageSize+"\");'/>"; 
           // html += " \n </div> \n ";
//            if(i >= 7){
//                return false;
//            }
        });
    }
    //在左上角显示图片
    $('#rool_list').html(html);
    //在产品描述后显示图片
    $('#productItemImageDesc').html(htmlDesc);
    $('#pic_small_area_list').html(hiddenBigHtml);
}

function showPrice(defaultItemId){   //show the price 
    //unit = $('#unitValueHidden').val();
    var hProductId = productData["item_"+defaultItemId].product_id;
    var listPrice = productData["item_"+defaultItemId].list_price;
    var salePrice = productData["item_"+defaultItemId].sale_price;
    var marketPrice = productData["item_"+defaultItemId].market_price;
//    if(listPrice == salePrice){
    	$('#marketPrice').html(marketPrice);
        $('#productSalePriceValue').html(salePrice);
//    	$('#productListPrice').show();
//        $('#productSalePrice').hide();
//        $('#productSave').hide();
//    }else{
//    	$('#productListPrice').show();
//        $('#productSalePrice').show();
//        $('#productSave').show();
//        savePrice = (listPrice - salePrice).toFixed(2);
//        savePercent = parseInt((savePrice / listPrice) * 100);
//        saveValue = savePrice + "(" + savePercent +"%)";
//        $('#productSalePriceValue').html(salePrice);
//        $('#productListPriceValue').html(listPrice);
//        $('#productSaveValue').html(saveValue);
//    }
    hidden = "";
    hidden += "<input id='hSalePrice' name='hSalePrice' type='hidden' value='"+salePrice+"' />";
    hidden += "<input id='hProductItemId' name='hProductItemId' type='hidden' value='"+defaultItemId+"' />";
    hidden += "<input id='hProductId' name='hProductId' type='hidden' value='"+hProductId+"' />";
    $('#hiddenValue').html("");
    $('#hiddenValue').html(hidden);
    //price = $(hidden);
    //price.appendTo('#hiddenValue');
}
/*
function showAttribute(defaultItemId){   //show the attribute value , for example : size attribute by different color
    html = "";
    tag = false; //attribute1 and value1 do not have value
    html += "<div id='productAttributes'>";
    html += "   <label> Select Attribute : </label>";
    //html += "   <div class='size_select'>";
    //html += "       <select id='size' name='size' onchange='javascript:changeAttribute(\""+this.value+"\");'>";
    html += "       <select name='attributes' onchange='javascript:changeAttribute(this.value);'>";
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            //get the all attribute and value
            attribute1 = productData[i].attribute_1 == null ? "" : productData[i].attribute_1;
            attribute2 = productData[i].attribute_2 == null ? "" : productData[i].attribute_2;
            attribute3 = productData[i].attribute_3 == null ? "" : productData[i].attribute_3;
            attribute4 = productData[i].attribute_4 == null ? "" : productData[i].attribute_4;
            attribute5 = productData[i].attribute_5 == null ? "" : productData[i].attribute_5;
            value1 = productData[i].value_1 == null ? "" : productData[i].value_1;
            value2 = productData[i].value_2 == null ? "" : productData[i].value_2;
            value3 = productData[i].value_3 == null ? "" : productData[i].value_3;
            value4 = productData[i].value_4 == null ? "" : productData[i].value_4;
            value5 = productData[i].value_5 == null ? "" : productData[i].value_5;
            if(attribute1 != null && value1 != null){
                if(attribute1.length != 0 && value1.length != 0){
                    tag = true;
                }
            }
            if(productData[i].id == defaultItemId){ //current showed item is selected
                html += "       <option value='"+productData[i].id+"' selected ='selected'>"+attribute1+" "+value1+" "+attribute2+" "+value2+" "+attribute3+" "+value3+" "+attribute4+" "+value4+" "+attribute5+" "+value5+"</option>";   
            }else{
                html += "       <option value='"+productData[i].id+"' >"+attribute1+" "+value1+" "+attribute2+" "+value2+" "+attribute3+" "+value3+" "+attribute4+" "+value4+" "+attribute5+" "+value5+"</option>";
            }
        }
    });
    html += "       </select>";
    //html += "   </div>";
    html += "</div>";
    $('#productAttribute').html("");
    if(tag){
        $('#productAttribute').html(html);
        //productAttr = $(html);
        //productAttr.appendTo('#productAttribute');
    }else{
        $('#productAttribute').html("<div class='attr'></div>");
        //productAttr = $("<div class='attr'></div>");
        //productAttr.appendTo('#productAttribute');
    }
}
*/

function selectDisabled(selectId){//set the select disable
    var selectId = Number(selectId);
    var attrNum = Number(productData["attr_num"]);
    for(var i = selectId + 1; i <= productData["attr_num"]; i++){
        $("#" + i).attr("disabled", true);
    }
}

function selectAbled(selectId){//set the select can use
    var selectId = Number(selectId);
    var attrNum = Number(productData["attr_num"]);
    var i = selectId + 1;
    $("#" + i).attr("disabled", false);
}

function generateSelect2Html(attrValue){//生成第二个下拉列表框的html并根据用户所选的第一个属性的值来确定itemid
    var defaultId;
    var selectLabel = $("#hSelectLabel").val();
    if(attrValue == -1){
        defaultId = productData.show_itemid;
        return defaultId+","+"0";
    }
    var attr2Value = Array();
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
        	if(productData[i].value_1 == attrValue){
            	var value2 = productData[i].value_2;
                attr2Value[productData[i].value_2] = productData[i].attribute_2_title;//na
                defaultId = productData[i].id;
            }
        }
    });
    var arratLength = 0
    for(var i  in attr2Value){
    	arratLength++;
    }
    var select2html = "\n <option value='-1'>"+selectLabel+"</option>";
    if(arratLength != 1){
    	select2html = "\n <option value='-1'>"+selectLabel+"</option>";
    }
    
    for(var i  in attr2Value){
        select2html += "<option value='"+ i +"'>"+ attr2Value[i] +"</option>";
    }
    $("#2").html(select2html);
    if( productData.attr_num == 1 ){//当前有效属性只有1个
    	return defaultId+","+defaultId;
    }else{
    	return defaultId+","+"0";
    }
    
}

function generateSelect3Html(attrValue){
    var defaultId;
    var selectLabel = $("#hSelectLabel").val();
    var attr3Value = Array();
    var selectFirstValue = $("#1").val();
    if(attrValue == -1){
        $.each(productData, function(i, obj){
            if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
                if(productData[i].value_1 == selectFirstValue){
                    defaultId = productData[i].id;
                }
            }
        });
        return defaultId+","+"0";
    }
    var select3html = "\n <option value='-1'>"+selectLabel+"</option>";
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == attrValue){
            	var value3 = productData[i].value_3;
                attr3Value[productData[i].value_3] = productData[i].attribute_3_title;//na
                defaultId = productData[i].id;
            }
        }
    });
    for(var i in attr3Value){
        select3html += "<option value='"+ i +"'>"+ attr3Value[i] +"</option>";
    }
    $("#3").html(select3html);
    if( productData.attr_num == 2 ){//当前有效属性只有3个
    	return defaultId+","+defaultId;
    }else{
    	return defaultId+","+"0";
    }
}

function generateSelect4Html(attrValue){
    var defaultId;
    var selectLabel = $("#hSelectLabel").val();
    var attr4Value = Array();
    var selectFirstValue = $("#1").val();
    var selectSecondValue = $("#2").val();
    if(attrValue == -1){
        $.each(productData, function(i, obj){
            if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
                if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == selectSecondValue){
                    defaultId = productData[i].id;
                }
            }
        });
        return defaultId+","+"0";
    }
    var select4html = "\n <option value='-1'>"+selectLabel+"</option>";
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == selectSecondValue && productData[i].value_3 == attrValue){
                var value4 = productData[i].value_4;
                attr4Value[productData[i].value_4] = productData[i].attribute_4_title;//na
                defaultId = productData[i].id;
            }
        }
    });
    for(var i in attr4Value){
        select4html += "<option value='"+ i +"'>"+ attr4Value[i] +"</option>";
    }
    $("#4").html(select4html);
    if( productData.attr_num == 3 ){//当前有效属性只有4个
    	return defaultId+","+defaultId;
    }else{
    	return defaultId+","+"0";
    }
}

function generateSelect5Html(attrValue){
    var defaultId;
    var selectLabel = $("#hSelectLabel").val();
    var attr5Value = Array();
    var selectFirstValue = $("#1").val();
    var selectSecondValue = $("#2").val();
    var selectThirdValue = $("#3").val();
    if(attrValue == -1){
        $.each(productData, function(i, obj){
            if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
                if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == selectSecondValue && productData[i].value_3 == selectThirdValue){
                    defaultId = productData[i].id;
                }
            }
        });
        return defaultId+","+"0";
    }
    var select5html = "\n <option value='-1'>"+selectLabel+"</option>";
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == selectSecondValue && productData[i].value_3 == selectThirdValue && productData[i].value_4 == attrValue){
                var value5 = productData[i].value_5;
                attr5Value[productData[i].value_5] = productData[i].attribute_5_title;//na
                defaultId = productData[i].id;
            }
        }
    });
    for(var i in attr5Value){
        select5html += "<option value='"+ i +"'>"+ attr5Value[i] +"</option>";
    }
    $("#5").html(select5html);
    if( productData.attr_num == 4 ){//当前有效属性只有2个
    	return defaultId+","+defaultId;
    }else{
    	return defaultId+","+"0";
    }
}

function getItemId(attrValue){//this is the five select
    var selectFirstValue = $("#1").val();
    var selectSecondValue = $("#2").val();
    var selectThirdValue = $("#3").val();
    var selectFourthValue = $("#4").val();
    if(attrValue == -1){
        $.each(productData, function(i, obj){
            if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
                if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == selectSecondValue && productData[i].value_3 == selectThirdValue && productData[i].value_4 == selectFourthValue){
                    defaultId = productData[i].id;
                }
            }
        });
        return defaultId+","+0;
    }
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            if(productData[i].value_1 == selectFirstValue && productData[i].value_2 == selectSecondValue && productData[i].value_3 == selectThirdValue && productData[i].value_4 == selectFourthValue && productData[i].value_5 == attrValue){  
                defaultId = productData[i].id;
            }
        }
    });
    return defaultId+","+defaultId;
}

function generateSelectValue(attrValue, selectId){
	var defaultId;
    if(selectId == 1){
    	defaultId = generateSelect2Html(attrValue);
    }else if(selectId == 2){
        defaultId = generateSelect3Html(attrValue);
    }else if(selectId == 3){
        defaultId = generateSelect4Html(attrValue);
    }else if(selectId == 4){
        defaultId = generateSelect5Html(attrValue);
    }else if(selectId == 5){
        defaultId = getItemId(attrValue);
    }
    return defaultId;
}

function changeAttribute(attrValue, selectId){//attrNum is how many availdate attribute number, selectId is current select control id     
    var selectId = Number(selectId);
    var defaultItemId;//生成默认图片的itemid
    var shoppingCartItemId = 0;//加入到购物车的itemid,shoppingCartItemId = 0则不允许加入到购物车直到能确定到一个item时shoppingCartItemId才赋值
    var result = Array();
	var itemIds;
    //akimimi setting for if first is color attr
    if(selectId == 1){
    	$("#1").val(attrValue);
    }
    
    ///////////////////////////////////////////////
    if(attrValue == "-1"){//if user select "-select-",then disable other select control
        selectDisabled(selectId);
        //defaultItemId = getPreviousSelectItemId(attrValue, selectId);
        itemIds = generateSelectValue(attrValue, selectId);
        result = itemIds.split(",");
    	defaultItemId = result[0];
    	shoppingCartItemId = result[1];
    }else{
        selectAbled(selectId);//set only back select can use
        selectDisabled(selectId+1);//set offside other select can not use
        //得到defaultitemid和shoppingcartid
    	itemIds = generateSelectValue(attrValue, selectId);
    	result = itemIds.split(",");
    	defaultItemId = result[0];
    	shoppingCartItemId = result[1];
    }
    
    
    
//    //generate the metadata by item id
//    generatePrimaryMetadataHtml(defaultItemId);
//    generateAllMetadataHtml(defaultItemId);
    
    //var defaultItemId = "";
    var imageSize = "400.jpg";
    var magnifySize = "800.jpg";
    var src;
    //var pubimgroot = productData.nullImgSrc.pubimgroot;
    //var templateName = productData.nullImgSrc.templateName;
    if(defaultItemId != 0){ //the DB already set the default value
        defaultSrc = productData["item_"+defaultItemId].main_image_url;
    }else{ //the DB not set the default_item value
        defaultItemId = productData.show_itemid;    //set the defaultItemId is random value
        defaultSrc = "";
        
    }
    if(defaultSrc == ""){
    	defaultSrc = "//i.akimimi.com/t/default_zh_cn/image/product_";
    }
    //if(defaultSrc != "" && defaultSrc != null){
        src = defaultSrc+imageSize;
    //}else{
    //    src = "http://"+pubimgroot+"/t/"+templateName+"/image/product"+"_"+imageSize;
    //}
        
    var srcs = productData["item_"+defaultItemId].image_url;
    showItemDefaultImg(defaultSrc, imageSize, magnifySize); //show the default image(the largest image)
	//show the diff view of default image(front , backend , side face)
    showItemOtherImg(srcs); 
    
    if( shoppingCartItemId != 0 ){//能够确认到唯一一个item此时shoppingCartItemId才有值
    	//show the product sale price
        showPrice(defaultItemId);   
        //showAttribute(defaultItemId);   //show the attribute image, ex: the different color and size
        showQuantity(defaultItemId);    //show the product quantity of inventory
        showShippingInfo(defaultItemId);    //show current item shipping info
        //change the hidden value
        $('#hSalePrice').val(productData["item_"+shoppingCartItemId].sale_price);
        $('#hProductItemId').val(shoppingCartItemId);
        //generate the metadata by item id
        generatePrimaryMetadataHtml(shoppingCartItemId);
        generateAllMetadataHtml(shoppingCartItemId);        
    }else{
    	$('#hProductItemId').val(shoppingCartItemId);
    }
	
    
    show_again();
    
}

function showShippingInfo(defaultItemId){
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            itemId = productData[i].id; //get the item id
            if(defaultItemId == itemId){//get the current item info
                shippingType = productData[i].shipping_type;
                freeShippingTitle = productData[i].free_shipping;
                if(shippingType == "NORMAL"){
                    if(freeShippingTitle != ""){
                        $('#noShipping').hide();
                        $('#freeShipping').show();
                        $('#freeShippingName').show();
                        $('#freeShippingName').html(freeShippingTitle);
                        $('#fixRateShipping').hide();
                        $('#fixRateShippingPrice').html("");
                    }else{
                        $('#noShipping').hide();
                        $('#freeShipping').hide();
                        $('#freeShippingName').hide();
                        $('#fixRateShipping').hide();
                        $('#fixRateShippingPrice').html("");
                    }
                }else if(shippingType == "FIX_RATE"){
                    $('#noShipping').hide();
                    $('#freeShipping').hide();
                    $('#freeShippingName').hide();
                    $('#fixRateShipping').show();
                    $('#fixRateShippingPrice').html(productData[i].shipping_fee);
                }else{
                    $('#noShipping').show();
                    $('#freeShipping').hide();
                    $('#freeShippingName').hide();
                    $('#fixRateShipping').hide();
                    $('#fixRateShippingPrice').html("");
                }
            }
        }
    });
    
}

function showQuantity(defaultItemId){
    //html = "";
    $.each(productData, function(i, obj){
        if(i.substring(0,4) == 'item'){ //while item_1 item_2 item_3 ...
            itemId = productData[i].id; //get the item id
            if(defaultItemId == itemId){//get the current item info
                quantity = productData[i].inventory; //get the color
                if(quantity == false){
                    $("#productAddToCart").attr('disabled',true);
                    $('#outOfStore').show();
                    $('#inStore').hide();
                    $('#productQuantityLabel').hide();
                    $('#productQuantitySelect').hide();
                }else{
                    $("#productAddToCart").attr("disabled",false);
                    $('#outOfStore').hide();
                    $('#inStore').show();
                    $('#productQuantityLabel').show();
                    $('#productQuantitySelect').show();
                    /*
                    html += "<select id='quantity' name='quantity'>";
                    for(var i=1; i <= quantity; i++){
                        html += "<option value="+i+">"+i+"</option>";
                    }
                    html += "</select>";
                    $('#productQualitySelect').html(html);
                    */
                }
            }
        }
    });
}

function unique(data){//data is a array
    data = data || [];
    var a = {};
    for (var i=0; i<data.length; i++) {
        var v = data[i];
        if (typeof(a[v]) == 'undefined'){
            a[v] = 1;
        }
    };
    data.length=0;
    for (var i in a){
        data[data.length] = i;
    }
    return data;
}
//akimimi generate the item metadata////////////
function generatePrimaryMetadataHtml(defaultItemId){
	$.ajax({
        type: 'post', 
        url: '/a/generatePrimaryMetadataHtml',
        dataType: "html",
        data: {"defaultItemId" : defaultItemId},
        async: true,
        success: function(data){
        	$("#primaryMetadataInfo").html(data);
        },
        error: function(){
        	$("#primaryMetadataInfo").html("");
        }
    });
}

function generateAllMetadataHtml(defaultItemId){
	$.ajax({
        type: 'post', 
        url: '/a/generateAllMetadataHtml',
        dataType: "html",
        data: {"defaultItemId" : defaultItemId},
        async: true,
        success: function(data){
        	$("#allMetadataInfo").html(data);
        },
        error: function(){
        	$("#allMetadataInfo").html("");
        }
    });
}



